<?php

//error_reporting(E_ALL);
//ini_set('display_errors', 1);

require_once(dirname(__FILE__) . '../../../config/config.inc.php');
require_once(dirname(__FILE__) . '../../../init.php');
//switch (Tools::getValue('method')) {


$shopId = 1;
$shopAddress = 'http://babymarket.bg';
$deliveryTime = 3;
$deliveryCost = 4;

$headers = array(
    // Mandatory Fields
    'code',
    'manufacturer',
    'category',
    'name',
    'product_url',
    'price',
    // Custom Fields
    'image_url',
    'image_url_2',
    'image_url_3',
    'description',
    'delivery_time',
    'delivery_cost',
);



$products = Db::getInstance()->ExecuteS("SELECT 
    ps_product.*,
    ps_product_lang.name            AS productName,
    ps_product_lang.description     AS productDescription,
    ps_product_lang.link_rewrite    AS productLinkRewrite,
    ps_category_lang.name           AS categoryName,
    ps_category_lang.link_rewrite   AS categoryLinkRewrite,
    ps_manufacturer.name            AS manufacturerName
FROM 
    ps_product 
LEFT JOIN
    ps_product_lang ON ps_product_lang.id_product=ps_product.id_product AND ps_product_lang.id_lang=2
LEFT JOIN 
    ps_category_lang ON ps_category_lang.id_category=ps_product.id_category_default AND ps_category_lang.id_lang=2
LEFT JOIN 
    ps_manufacturer ON ps_manufacturer.id_manufacturer=ps_product.id_manufacturer
WHERE
    ps_product.id_shop_default={$shopId}");

//echo Db::getInstance()->getMsgError();
//echo "<pre>"; die(var_dump($products));
// FORMAT
// "code", "manufacturer", "name", "description", "price", "category", "image_url", "product_url"


/*
 * Send Http Headers
 */
$now = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");

// force download  
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");

// disposition / encoding on response body
header("Content-Disposition: attachment;filename=export.csv");
header("Content-Transfer-Encoding: binary");


ob_start();
$df = fopen("php://output", 'w');
fputcsv($df, $headers);
foreach ($products as $row) {

    $csvRow = array(
        $row['reference'],
        $row['manufacturerName'],
        $row['categoryName'],
        $row['productName'],
        sprintf('%s/%s/%d-%s.html', $shopAddress, $row['categoryLinkRewrite'], $row['id_product'], $row['productLinkRewrite']),
        $row['price'],
        '',
        '',
        '',
        '',
        $deliveryTime,
        $deliveryCost
    );

    fputcsv($df, $csvRow);
}

fclose($df);

echo ob_get_clean();
